#include<stdio.h>
#include<assert.h>
typedef struct student
{
	char name[20];
	int english;
	int math;
	int c_total_mark;
}Stu;

int ReadFile(Stu s[]){
	FILE *p = fopen("students.txt", "r+");
	if (!p) {
		perror("open file error:");
		assert(0);
	}
	int count = 0;
	while (!feof(p)) {
		fscanf(p, "%s%d%d%d", s[count].name, &s[count].english, &s[count].math, &s[count].c_total_mark);
		count++;
	}
	fclose(p); 
	return count;
}
void PutInFile(Stu s[], int count){
	FILE* fp = fopen("students.txt", "r+");
	if (!fp) {
		perror("open file error:");
		assert(0);
	}
	fprintf(fp, "%12s%12s%12s%12s\n", "Name", "English", "Math", "CTotal");
	for (int i = 0; i < count; i++)
		fprintf(fp, "%12s%12d%12d%12d%12d\n", s[i].name, s[i].english, s[i].math, s[i].c_total_mark, (s[i].english + s[i].math + s[i].c_total_mark));
}
void MyOrder(Stu s[], int count) {
	int i, j, flag;
	for (i = 0; i < count - 1; i++) {
		flag = 0;
		for (j = 0; j < count - i - 1; j++) {
			int sum1 = s[j].english + s[j].math + s[j].c_total_mark;
			int sum2 = s[j + 1].english + s[j + 1].math + s[j + 1].c_total_mark;
			if (sum1 < sum2) {
				Stu temp= s[j];
				s[j] = s[j + 1];
				s[j + 1] = temp;
				flag = 1;
			}
		}
		if (!flag)
			break;
	}
}
int main() { 
	Stu s[50] = { 0 };
	int count = ReadFile(s);
	MyOrder(s, count);
	PutInFile(s, count); 
	return 0; 
}
